<template>
    <div>
      <el-collapse v-model="activeNames" accordion  v-loading="loading" :element-loading-text="loadingText">
        <el-collapse-item title="Amenity Category List" name="1"  style="padding-left: 15px;">
          <el-tag style="margin: 5px 5px"
            v-for="(tag, index) in dataList"
            closable
            :type="(index+1 % 1 == 0) ? 'success' : (index % 2 == 0) ? 'info' : (index % 3 == 0) ? 'warning' : (index % 4 == 0) ? 'danger' : ''"
           @click="clickTag(tag.id)" @close="closeTag(tag.id)">
            {{tag.name}}
          </el-tag>

        </el-collapse-item>
        <el-collapse-item title="Add New Amenity" name="2" style="padding-left: 15px;">
          <el-form ref="formData" :model="formData" :rules="rules" label-width="125px" class="form-wrap">
            <el-form-item label="Name" prop="name">
              <el-input v-model="formData.name" placeholder="Please Enter Name"></el-input>
            </el-form-item>

            <el-form-item label="Description" prop="description">
              <el-input
                type="textarea"
                placeholder="Please Enter Description"
                v-model="formData.description"
                rows="8"
                maxlength="1000"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item style="text-align: center;">
              <el-button type="primary" @click="doSave">Save Changes</el-button>
              <el-button @click="doReset">Reset Form</el-button>
              <el-button @click="doExpandAll">All Expand</el-button>
            </el-form-item>

          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>
</template>

<script>
    import {addModel,searchModel,get,updateModel,deleteModel} from "@/api/model";
    export default {
        name: "EditManageAmenitiesForm",
        data() {
            return {
                model: 'PhysicalRoomAmenityCategory', //（物理客房设施类别）
                bodyHeight:900,
                parentObj : null, //父对象
                loading:false,
                loadingText:'data load ...',
                activeNames: ['1','2'],
                dataList:[],
                cacheDataList:[],
                formData: this.getInitFormData(),
                rules: this.getInitRules()
            }
        },
        created() {
            const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // console.log("bodyHeight="+_bodyHeight);
            this.bodyHeight = _bodyHeight - 65;
        },
        mounted(){
            this.loadDatas();
        },
        methods: {
            getInitFormData(){
                return  {
                    id:null,
                    name:null,//      字符串 最大64字符。
                    description:null,//    字符串 最大64字符。
                };
            },
            getInitRules() {
                return {
                    name: [
                        {required: true, message: 'Please Enter Name', trigger: 'blur'},
                        {min: 2, max: 64, message: '2 to 60 characters in length', trigger: 'blur'}
                    ],
                    description: [
                        {required: true, message: 'Please Enter Description', trigger: 'blur'},
                        {min: 2, max: 64, message: '2 to 2000 characters in length', trigger: 'blur'}
                    ]
                }
            },
            refresh(_parentObj){
                console.log("refresh to do ...");
                this.parentObj = _parentObj;
                this.loadDatas();
            },
            /**
             * 加载数据
             */
            loadDatas(){
                console.log("loadDatas to do ...");
                this.dataList = [];
                this.cacheDataList = [];
                this.doReset();
                this.loadAmenityCategories();
            },
            loadAmenityCategories(isLoadParent){
                let _this = this;
                this.loading = true;
                const _parent = _this.parentObj || _this.$parent;
                searchModel(this.model, {
                    search_keys:{}
                }).then(res => {
                    _this.loading = false;
                    if(!res || !res.data){
                        _this.cacheDataList = [];
                        _this.dataList = [];
                        return;
                    }
                    const list = res.data.list;
                    _this.cacheDataList = list;
                    _this.dataList = list.map( item => {
                        return {id: item.id, name: item.name};
                    });
                    if(isLoadParent){ //加载父页面的多选下拉列表
                        _parent.transferAmenitiesList(list);
                    }
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            /**
             *  删除
             * */
            doDel(id){
                const _this = this;
                this.loading = true;
                this.loading = true;
                deleteModel(this.model, id).then(res => {
                    console.log("doDel success ...");
                    console.log(res);
                  _this.loadAmenityCategories(true);
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            /**
             *
             * 保存数据
             */
            doSave(){
                console.log("doSave to do ...");
                const _this = this;
                console.log(this.formData);
                let _formData = this.formData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }

                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                        _this.loading = true;
                        if(_this.formData.id){
                            updateModel(this.model, _this.formData.id, _formData).then(res => {
                                _this.loading = false;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                _this.loadAmenityCategories(true);
                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                //_this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }else{
                            const jsonStr =  JSON.stringify(_formData);
                            addModel(this.model, jsonStr).then(res => {
                                console.log(res);
                                const _id = res.data.id;
                                _this.formData.id = _id;
                                _this.loading = false;
                                _this.$message({
                                    type: 'info',
                                    message: 'Save Data Success!'
                                });
                                _this.loadAmenityCategories(true);

                            }).catch(reason => {
                                _this.loading = false;
                                console.log("doSave Failure...");
                                console.log(reason);
                                // _this.$message.error('Please Check Input Form Data Has Errors!');
                            });
                        }
                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });

            },
            doExpandAll(){
                this.activeNames = ['1','2'];
            },
            /**
             * 点击Tag
             */
            clickTag(id){
                console.log("clickTag.id="+id);
                for(let i=0,count=this.cacheDataList.length; i<count; i++){
                    const data = this.cacheDataList[i];
                    const _id = data.id;
                    if(_id == id){
                        this.formData = data;
                        break;
                    }
                }
            },
            /**
             * 关闭Tag
             */
            closeTag(id){
                console.log("closeTag.id="+id);
                this.doDel(id);
            },
            /**
             * 重置表单
             */
            doReset(){
                this.formData = this.getInitFormData();
            }
        }
    }
</script>

<style scoped>
  .form-wrap{
    padding: 0px 20px;
  }
</style>
